/**
 * Copyright (C) 2015 kmy-framework-base Project
 *               Author: Chris
 *               Date: 2015年11月7日
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zmq.ha.client.core;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;

/**
 * Name: PublisherPool.java
 * ProjectName: [kmy-framework-base]
 * Package: [com.kmy.framework.rabbitmq.recover.core.PublisherPool.java]
 * Description: TODO  
 * 
 * @since JDK1.7
 * @see
 *
 * @author: Chris
 * @date: 2015年11月7日 下午4:59:45
 *
 * Update-User: @author
 * Update-Time:
 * Update-Remark:
 * 
 * Check-User:
 * Check-Time:
 * Check-Remark:
 * 
 * Company: kmhc
 * Copyright: kmhc
 */
public class PublisherPool {
	
	private ThreadLocal<ExecutePublisher> publishPool = new ThreadLocal<ExecutePublisher>();
	
	final Channel channel;
	
	final String exchange;
	final String severity;
	final String queueName;
	
	
	/** 
	 * @Title: PublisherPool
	 * @Description: TODO
	 * @param @param publishPool
	 * @param @param channel
	 * @param @param exchange
	 * @param @param severity
	 * @param @param queueName
	 * @param @param consumerName         
	 * @throws 
	 */ 
	public PublisherPool(Channel channel, String exchange, String severity,
			String queueName ) {
		this.channel = channel;
		this.exchange = exchange;
		this.severity = severity;
		this.queueName = queueName;
		
	}
	
	public void closeAllChannel(){
		try {
			channel.close();
		} catch (IOException | TimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ExecutePublisher getPublisher(){
		
		try {
			
			ExecutePublisher publisher = this.publishPool.get();
		    if( publisher != null ) return publisher;
		 
		    if( queueName != null ){
				//该处MQ自身有幂等操作，如果出现了queue，则不会发生操作，避免没有生存者没有绑定queue
				channel.queueDeclare(queueName, true, false, false, null);
			}
			
			if(exchange!=null ){
				channel.exchangeDeclare(this.exchange,"direct",true);
			}
			
			if(queueName!= null&&exchange!= null ){				
				channel.queueBind(queueName, exchange, severity);	
			}
			
			ExecutePublisher newPublisher = new ExecutePublisher(channel, exchange, severity);
			publishPool.set(newPublisher);
			return publishPool.get();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
				
	}

}

	
